package com.wq.concurrency.aqs;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wangqiang20995
 * @Date:2019/8/19
 * @Description:
 * @Resource:
 */
public class SemaphoreSingThreadDemo {

    private static class InnerClass {
        private Map<String,String> map;

        public void setMap(Map<String,String> map){
            this.map = map;
        }

        public Map<String, String> getMap() {
            return map;
        }

        @Override
        public String toString() {
            return "InnerClass{" +
                    "map=" + map +
                    '}';
        }
    }

    public static void main(String[] args){
//        semaphoreTest();

//        LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(3);
//        for(int i=0;i<5;i++){
//            boolean b = queue.offer(String.valueOf(i));
//            System.out.println(b);
//        }

//        for(int i=0;i<100;i++) {
//            new Thread(()->System.out.println(getTransferStartDate("20190816", "5"))).start();
//        }

        InnerClass innerClass = new InnerClass();
        Map<String,String> map = new HashMap<>();
        map.put("settledate","1");
        innerClass.setMap(map);
        for(int i=0;i<10;i++){
            innerClass.getMap().put("settledate",String.valueOf(i+1));
            System.out.println(innerClass);
        }

        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");

        List<String> sub = list.subList(1,2);
        list.add("5");
        for(String t:sub){
            System.out.println(t);
        }

    }

    private static void semaphoreTest() {
        Semaphore semaphore = new Semaphore(3);
        for(int i = 0;i<5;i++){
            try{
                /**
                 * 下面这段代码会发生死锁，因为当前只有一个线程main，它执行了四次semaphore#acquire方法
                 * 同时因为semaphore的信号量是3，所以在执行第四次的时候，就阻塞了
                 */
                semaphore.acquire();
                System.out.println("模拟发送到服务端-0...");
                semaphore.acquire();
                System.out.println("模拟发送到服务端-1...");
                semaphore.acquire();
                System.out.println("模拟发送到服务端-2...");
                semaphore.acquire();
                System.out.println("模拟发送到服务端-3...");
                TimeUnit.SECONDS.sleep(1);
                System.out.println("done");
                semaphore.release();
                semaphore.release();
                semaphore.release();
                semaphore.release();
            } catch (InterruptedException e) {
                System.out.println("中断异常...");
            }
        }
    }
}
